package simple.cat.server;

import simple.cat.servlet.HttpServlet;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;

/**
 * @author zheng9feng
 * @Description 请求处理线程实现类
 * @Date 2020/12/29 23:59
 */
public class RequestProcessor extends Thread {
	
	private Socket socket;
	private Map<String, HttpServlet> servletMap;
	
	public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
		this.socket = socket;
		this.servletMap = servletMap;
	}
	
	@Override
	public void run() {
		try {
			System.out.println("current thread:" + Thread.currentThread().getName());
			// 请求封装
			InputStream inputStream = socket.getInputStream();
			Request request = new Request(inputStream);
			// 响应封装
			OutputStream outputStream = socket.getOutputStream();
			Response response = new Response(outputStream);
			
			String url = request.getUrl();
			// 根据url判断是静态资源请求还是动态资源请求
			// 如果存在与url映射的servlet实例说明是动态请求,否则就是静态请求
			HttpServlet httpServlet = servletMap.get(url);
			if (httpServlet == null) {
				response.buildResourceAbsolutePath(url);
				// 输出静态资源文件
				response.outputHtml();
				
			} else {
				httpServlet.service(request, response);
			}
			
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
